package starwars.example;

import java.util.ArrayList;
import java.util.Iterator;

import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.extension.physics.box2d.PhysicsConnector;
import org.anddev.andengine.extension.physics.box2d.PhysicsFactory;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;

import starwars.example.Item.CollectionHandler;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

public class Field extends PhysicsWorld{

	Scene scene;
	
	public Field(Vector2 pGravity, boolean pAllowSleep) {
		super(pGravity, pAllowSleep);
	}

	public void attachScene(Scene scene, float CAMERA_WIDTH,float CAMERA_HEIGHT){
		this.scene=scene;
		
		//attach rectangle border
		final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2);
		final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2);
		final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT);
		final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT);
		final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
		PhysicsFactory.createBoxBody(this, ground, BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this, roof, BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this, left, BodyType.StaticBody, wallFixtureDef);
		PhysicsFactory.createBoxBody(this, right, BodyType.StaticBody, wallFixtureDef);
		scene.attachChild(ground);
		scene.attachChild(roof);
		scene.attachChild(left);
		scene.attachChild(right);

		// attach grid
		for(int x=0;x<CAMERA_WIDTH;x=x+50){
			scene.attachChild(new Line(x, 0, x, CAMERA_HEIGHT));
		}
		
		for(int y=0;y<CAMERA_HEIGHT;y=y+50){
			scene.attachChild(new Line(0, y, CAMERA_WIDTH, y));
		}
		
	}
	
	ArrayList<Item> items = new ArrayList<Item>();

	public void add(Item item){
		this.registerPhysicsConnector(new PhysicsConnector(item.sprite,item.body, true, true));
		items.add(item);
	}
	

	public void forEachItem(String type,CollectionHandler c){
		Iterator<Item> itr = items.iterator();
		while(itr.hasNext()){
			Item a=itr.next();
			if(a.type.equals(type)){
				c.analyse(a);
			}
		}
	}
}
